package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.CartAddUuBean;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/3 16:23
 */
public class Dws_06_DwsTradeCartAddUuWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_06_DwsTradeCartAddUuWindowApp()
            .init(
                "Dws_6_DwsTradeCartAddUuWindowApp",
                4006,
                1,
                "Dws_6_DwsTradeCartAddUuWindowApp",
                "Dws_6_DwsTradeCartAddUuWindowApp",
                "dwd_trade_cart_add"
            );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        /*
        加购独立用户
            从加购表中读取数据,
                使用状态
         */
        stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getString("user_id"))
            .process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {
                
                private ValueState<String> lastCartAddDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastCartAddDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastCartAddDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<CartAddUuBean> out) throws Exception {
                    String today = DateFormatUtil.toDate(value.getLong("ts") * 1000);
                    String lastCartAddDate = lastCartAddDateState.value();
                    
                    if (!today.equals(lastCartAddDate)) {
                        out.collect(new CartAddUuBean("", "", 1L, value.getLong("ts") * 1000));
                        lastCartAddDateState.update(today);
                    }
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<CartAddUuBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;
                    }
                },
                new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<CartAddUuBean> values,
                                      Collector<CartAddUuBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        Long ts = System.currentTimeMillis();
                        
                        CartAddUuBean result = values.iterator().next();
                        result.setStt(stt);
                        result.setEdt(edt);
                        result.setTs(ts);
                        
                        out.collect(result);
                    }
                }
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("gmall2022", "dws_trade_cart_add_uu_window", CartAddUuBean.class));
        
        
    }
}
